package com.txw.travel.security;

import com.txw.travel.pojo.Admin;
import com.txw.travel.pojo.Permission;
import com.txw.travel.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取用户
        Admin admin = adminService.getAdminByName(username);

        if (admin == null)
            throw new UsernameNotFoundException("用户不存在");

        if (!admin.isStatus())
            throw new UsernameNotFoundException("用户已被锁定");

        List<Permission> adminPermissions = adminService.getAdminPermissions(username);
        List<GrantedAuthority> GrantedAuthorities = new ArrayList();
        for (Permission permission : adminPermissions) {
            GrantedAuthorities.add(new SimpleGrantedAuthority(permission.getPermissionDesc()));
        }

        UserDetails user = User.withUsername(admin.getUsername())
                .password(admin.getPassword())
                .authorities(GrantedAuthorities)  //授权
                .build();

        return user;
    }
}
